/*
 * Copyright (C) 2012 Atlas of Living Australia
 * All Rights Reserved.
 *
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 */
package au.org.ala.phylojive

import org.codehaus.groovy.grails.web.json.JSONObject
import grails.converters.JSON

class ProxyController {
    def webService
    def batchSize = 100

    def getCharacters() {
        def names = params.names.replaceAll(" ", "+")
        def dataset = params.dataset
        def url = grailsApplication.config.identifyLifeUrl + "?t=" + names + "&d=" + dataset
        def json = webService.get(url)
        def jsonObj = JSON.parse(json.toString())
        log.debug "jsonObj type = " + jsonObj.getClass()

        if (jsonObj instanceof JSONObject && true && jsonObj.has("error")) {
            log.debug "json = " + json
            //response.status = 500
            //render (contentType: "application/json", text: json)
            render(status: 500, text: jsonObj.error)
        } else if (params.callback) {
            render (contentType: "application/javascript", text: "${params.callback}(${json})")
        } else {
            render (contentType: "application/json", text: json)
        }
    }

    /**
     * Sends batched-up requests to Identify Life, so as to overcome limits of long GET URLs
     *
     * @return
     */
    def getCharactersPost() {
        def names = params.names?.replaceAll(" ", "+")
        def dataset = params.dataset
        def namesList = names?.split(";") as List
        def pagedNames = namesList.collate(batchSize) // batch up
        def jsonResult = new JSONObject() // batched results get added to this

        pagedNames.eachWithIndex { group, i ->
            //log.debug i + " paging taxa..." + group.size()
            def url = grailsApplication.config.identifyLifeUrl + "?t=" + group.join(";") + "&d=" + dataset
            def jsonObj = JSON.parse(webService.get(url))

            jsonObj.each {
                // add to jsonResult
                jsonResult.put(it.key, it.value);
            }
        }

        render (contentType: "application/json", text: jsonResult.toString())
    }
}
